package ca.uwo.android.directoryservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;

import ca.uwo.android.sslconnection.WesternHttpClient;

public class DirectoryConnectionHandler {
	public int LastResponseCode;
	private WesternHttpClient httpClient;

	public DirectoryConnectionHandler(WesternHttpClient client) {
		httpClient = client;
	}

	JSONArray DSearch(String query) throws Exception {
		String result = null;
		JSONArray jArray = null;
		LastResponseCode = 0;

		try {
			HttpParams httpParameters = new BasicHttpParams();
			// Set the timeout in milliseconds until a connection is established
			int timeOutConnection = 10000;
			HttpConnectionParams.setConnectionTimeout(httpParameters,
					timeOutConnection);
			// Set the default socket timeout (SO_TIMEOUT)
			// in milliseconds which is the timeout for waiting for data.
			int timeOutSocket = 10000;
			HttpConnectionParams.setSoTimeout(httpParameters, timeOutSocket);
			// instantiate the custom http client
			httpClient = new WesternHttpClient(httpParameters);
			HttpGet httpGet = new HttpGet(query);
			HttpResponse httpResponse = httpClient.execute(httpGet);
			HttpEntity entity = httpResponse.getEntity();
			LastResponseCode = httpResponse.getStatusLine().getStatusCode();
			if (LastResponseCode == 500) {
				throw new Exception("Internal server error:  "
						+ httpResponse.getStatusLine());
			}

			InputStream input = entity.getContent();

			BufferedReader br = new BufferedReader(new InputStreamReader(input));
			StringBuilder sb = new StringBuilder();

			while ((result = br.readLine()) != null)
				sb.append(result + "\n");

			result = sb.toString();

			if (LastResponseCode == 400) {
				throw new Exception(result);
			}

			jArray = new JSONArray(result);
			if (jArray.length() == 0)
				throw new Exception("No Match Found");
		} catch (IOException e) {
			throw new Exception("Connection Error, Please Try Again Later");
		} catch (JSONException e) {
			throw new Exception("Data Corrupted, Please Try Again Later");
		} catch (IllegalArgumentException e) {
			throw new Exception("Illegal Character");
		}

		return jArray;
	}
}